package com.kanshu.ksgb.fastread.doudou.module.message.receiver;

import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.common.util.ARouterUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.ActivityMgr;
import com.kanshu.ksgb.fastread.doudou.common.util.JsonUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.OSUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.StorageUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.module.message.utils.MessageUtils;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.MessageBean;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.NotifyBean;
import com.kanshu.ksgb.fastread.doudou.module.message.manager.MessageCenter;

import org.json.JSONObject;

import cn.jpush.android.api.JPushInterface;

/**
 * 极光推送接受广播器
 */
public class JPushReceiver extends BroadcastReceiver {
    private static final String TAG = "JPush";
    @Override
    public void onReceive(final Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        Log.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: ");

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
            //send the Registration Id to your server...
            StorageUtils.setPreference(context, Constants.SP_NAME, Constants.JPUSH_REG_ID, regId, true);

        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            String msg = bundle.getString(JPushInterface.EXTRA_MESSAGE);
            Log.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + msg);
            handleCustomMsg(msg);

        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 接收到推送下来的通知");
            int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            String string = bundle.getString(JPushInterface.EXTRA_EXTRA);
            Log.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);
            //service.cancel(notifactionId);
            //handleCustomNotifaction(context, string);

        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 用户点击打开了通知");
            Bundle extras = intent.getExtras();
            String string = bundle.getString(JPushInterface.EXTRA_EXTRA);
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(string);
                String notify = jsonObject.getString("notify");
                final Intent i = new Intent();
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                NotifyBean messageBean = JsonUtils.json2BeanByFastJson(notify, NotifyBean.class);
                boolean flg = MessageCenter.createIntent(context, i, messageBean);
                if (OSUtils.isEMUI()) {
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.postDelayed(() -> {
                        if (flg){
                            context.startActivity(i);
                        }
                    }, 2000);
                } else  {
                    Utils.jumpToHomeIfNeed();
                    if (flg){
                        context.startActivity(i);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
            //Log.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
            //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

        } else if(JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            Log.w(TAG, "[MyReceiver]" + intent.getAction() +" connected state change to "+connected);
        } else if (Constants.PUSH_RECEIVER_ACTION.equals(intent.getAction())) {
            handleCustomNotify(context, intent);
        }
        else {
            Log.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
        }
    }


    /**
     * 处理自定义消息
     * @param msg
     */
    private void handleCustomMsg(String msg) {
        try {
            JSONObject jsonObject = new JSONObject(msg);
            String s = jsonObject.toString();
            MessageBean messageBean = JsonUtils.json2Bean(s, MessageBean.class);
            MessageCenter.getInstance().handleMessage(messageBean);
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG, "handleCustomMsg exception:" + e.getMessage());
        }
    }

    /**
     * 处理自定义通知
     * @param context
     * @param intent
     */
    private void handleCustomNotify(Context context, Intent intent) {
        Intent realIntent = intent.getParcelableExtra("realIntent");
        if (realIntent != null && context != null) {
            int notify_id = realIntent.getIntExtra("message_id", 1);
            if (ActivityMgr.getInstance().getActivityCount() <= 1) {
                ARouterUtils.toActivity(ARouterConfig.HOME_PAGE);
            }
            context.startActivity(realIntent);
            MessageUtils.countMessageClick(notify_id + "", 0);
        }
    }

    /**
     * 处理自定义通知栏
     * @param context
     * @param bundle
     */
    private void handleCustomNotifaction(final Context context, final String bundle) {
        try {
            JSONObject jsonObject = new JSONObject(bundle);
            String notify = jsonObject.getString("notify");
            NotifyBean messageBean = JsonUtils.json2BeanByFastJson(notify, NotifyBean.class);
            if (messageBean != null) {
                MessageCenter.getInstance().sendNotification(context, messageBean);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
